package com.qianjiangcloud.store.activity.account;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qianjiangcloud.store.AgentApplication;
import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.activity.AgentActivity;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;
import com.qianjiangcloud.store.util.Util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import com.qianjiangcloud.store.R;
import com.qianjiangcloud.store.wxapi.WXPayEntryActivity;
import cn.shopex.pay.AliPayHandle;
import cn.shopex.pay.AliPayInfo;
import cn.shopex.pay.WeChatPayHandle;
import cn.shopex.pay.WeiXinPayInfo;
import cn.shopex.pay.client.PayResult;

public class ChargeMethods extends BaseDoFragment implements WXPayEntryActivity.PayStateCallBack, AliPayHandle.PayResultListener {

    private LayoutInflater mInflater;
    private LinearLayout mContainer;
    private Button btnNext;//确认充值或下一步
    private TextView tvChooseBank;
    private CheckBox cbAliPay;
    private CheckBox cbWeChat;
    private EditText etInput;
    private JSONObject payInfo = null;
    private JSONObject obj = null;
    private View v;
    JSONObject all = null;
    private boolean mPaymentStatus = false;
    private LinearLayout mChargeLinearLayout;
    private WeChatPayHandle weChatPayHandle;
    public ChargeMethods() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActionBar.setTitle(R.string.account_center);
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
        super.init(inflater, container, savedInstanceState);
        mInflater = inflater;
        rootView = inflater.inflate(R.layout.fragment_account_pay_new, null);
        mContainer = (LinearLayout) rootView.findViewById(R.id.fragment_charge_methods_container);
        mChargeLinearLayout = (LinearLayout) findViewById(R.id.ll_charge);
        btnNext = (Button) findViewById(R.id.btn_next);
        etInput = (EditText) findViewById(R.id.charge_count);
        btnNext.setOnClickListener(this);
        new JsonTask().execute(new GetChargeTerms());
    }

    private void updatePayView(JSONArray list) {

        List<JSONObject> mListObj = new ArrayList<JSONObject>();

        for (int i = 0; i < list.length(); i++) {
            JSONObject objs = list.optJSONObject(i);
            if (TextUtils.equals("wxpaysdk", objs.optString("app_id")) || TextUtils.equals("malipay", objs.optString("app_id"))) {
//            if (!"deposit".equals(obj.optString("app_id"))) {
                v = mInflater.inflate(R.layout.view_charge_item_new, null);
                ImageView img = (ImageView) v.findViewById(R.id.view_charge_item_pay_icon);
                img.setImageResource("wxpaysdk".equals(objs.optString("app_id")) ? R.drawable.icon_weixin : R.drawable.icon_alipay);
                img.setTag(i);
                mListObj.add(objs);
//                mVolleyImageLoader.showImage(img, obj.optString("icon_src"));
//                TextView txt = (TextView) v.findViewById(R.id.view_charge_item_pay_name);
//                txt.setText(obj.optString("app_name"));
                v.setTag(objs);
                mContainer.addView(v);
                v.setOnClickListener(mPayListener);

            }


        }
//        mContainer.getChildAt(0).setPressed(true);
//        ViewGroup items = ((ViewGroup) findViewById(R.id.confirm_order_pay_items));
        if (mContainer.getChildCount() > 0) {
            payInfo = mListObj.get(0);
            obj = mListObj.get(0);
            Log.i("objs", obj.toString());
            ((CheckBox) mContainer.getChildAt(0).findViewById(R.id.cb_account_choose_alipay)).setChecked(true);
            if (mActivity != null && isAdded())
                ((ViewGroup) mContainer.findViewById(R.id.fragment_charge_methods_container)).getChildAt(0).findViewById(R.id.view_charge_item_wechat).setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_enter_view_press));
        }


    }

    @Override
    public void onClick(View v) {
        if (v.getTag() != null) {
            JSONObject data = (JSONObject) v.getTag();
            ViewGroup items = ((ViewGroup) findViewById(R.id.confirm_order_pay_items));

            // 选中当前付款方式
            payInfo = data;
            for (int i = 0, c = items.getChildCount(); i < c; i++)
                ((CheckBox) items.getChildAt(i).findViewById(R.id.confirm_order_pay_checkbox)).setChecked(false);
            ((CheckBox) v.findViewById(R.id.confirm_order_pay_checkbox)).setChecked(true);
        }

        if (v == btnNext) {
            if (TextUtils.isEmpty(etInput.getText().toString().trim())) {
                Run.alert(mActivity, R.string.charge_amt_hint);
                return;
            }
            double input = Double.parseDouble(etInput.getText().toString().trim());
            if (input <= 0) {
                Run.alert(mActivity, R.string.charge_amt_hint_new);
                return;
            }
//            防止没有选中充值方式就充值出现的崩溃情况
            if (obj == null || obj.optString("app_id").isEmpty()) {
                Run.alert(mActivity, R.string.charge_amt_hint_meth);
                return;
            }

            JsonRequestBean bean = buildCreateOrderRequestBean(payInfo);
            weChatPayHandle = new WeChatPayHandle(getActivity());
            if (payInfo.optString("app_id").equalsIgnoreCase("wxpaysdk")) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("payment_cur_money", String.valueOf(input));
                    jsonObject.put("pay_object", "recharge");
                    jsonObject.put("payment_pay_app_id", obj.optString("app_id"));
                    WXPayEntryActivity.setPayStateCallBack(ChargeMethods.this);
                    weChatPayHandle.callWXPay(jsonObject, "mobileapi.pay.weixinpay", Run.API_URL, Run.TOKEN);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (payInfo.optString("app_id").equalsIgnoreCase("malipay")) {
                Run.excuteJsonTask(new JsonTask(), new DoPaymentTask(bean));
            }
        }
        super.onClick(v);
    }

    @Override
    public void weixinPayResult(boolean state) {
        // 微信支付结果回调
        if (state) {
            JsonRequestBean bean = new JsonRequestBean("mobileapi.paycenter.confirm_pay_status")
                    .addParams("pay_app_id", "wxpaysdk")
                    .addParams("payment_id", weChatPayHandle.getPaymentid());
            Run.excuteJsonTask(new JsonTask(), new CheckPayTask(bean));

        } else {
//            Run.alert(getActivity(), "支付失败");
            resetPaymentStatusView();
        }
    }

    @Override
    public void aliPayResult(PayResult payResult) {
        // 支付宝支付结果回调
        String resultStatus = payResult.getResultStatus();

        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
        if (TextUtils.equals(resultStatus, "9000")) {
            Toast.makeText(mActivity, "支付成功", Toast.LENGTH_SHORT).show();
//                    getActivity().finish();
            mPaymentStatus = true;
        } else {
            // 判断resultStatus 为非“9000”则代表可能支付失败
            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
            if (TextUtils.equals(resultStatus, "8000")) {
                Toast.makeText(mActivity, "支付结果确认中", Toast.LENGTH_SHORT).show();

            } else {
                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                // Toast.makeText(mActivity, "支付失败", Toast.LENGTH_SHORT)
                // .show();
                // startActivity(AgentActivity.intentForFragment(mActivity,
                // AgentActivity.FRAGMENT_ACCOUNT_ORDERS).putExtra(
                // Run.EXTRA_VALUE, 0));
                mPaymentStatus = false;
            }
        }
        resetPaymentStatusView();
    }

    public class DoPaymentTask implements JsonTaskHandler {
        private JsonRequestBean bean;

        public DoPaymentTask(JsonRequestBean bean) {
            this.bean = bean;
        }

        @Override
        public void task_response(String json_str) {
            try {
                hideLoadingDialog_mt();
                JSONObject all = new JSONObject(json_str);
                Log.i("json_str", json_str);
                if (Run.checkRequestJson(mActivity, all)) {
                    String payName = all.optJSONObject("data").optString("pay_app_id");
                    Log.i("payName", payName);
                    JSONObject data = all.optJSONObject("data");
                    if (payName.equals("malipay")) {
                        AliPayInfo aliPayInfo = new AliPayInfo();
                        aliPayInfo.setPartner(data.optString("mer_id"));
                        aliPayInfo.setSeller(data.optString("seller_account_name"));
                        aliPayInfo.setRsa_private(data.optString("key"));
                        aliPayInfo.setNotify_url(data.optString("callback_url"));
                        aliPayInfo.setPrice(data.optString("total_amount"));
                        aliPayInfo.setOrder_id(data.optString("payment_id"));
                        try {
                            AliPayHandle aliPayHandle = new AliPayHandle(getActivity(), aliPayInfo);
                            aliPayHandle.setPayResultListener(ChargeMethods.this);
                        } catch (AliPayHandle.APliPaySetingInfoNullException e) {
                            e.printStackTrace();
                        }
                        return;
                    } else if (payName.equals("wxpaysdk")) {
                        JSONObject order = data.optJSONObject("order");
                        WXPayEntryActivity.setPayStateCallBack(ChargeMethods.this);
                        WeChatPayHandle weChatPayHandle = new WeChatPayHandle(getActivity());
                        WeiXinPayInfo weiXinPayInfo = new WeiXinPayInfo();
                        weiXinPayInfo.setOrderid(order.optString("order_id"));
                        weiXinPayInfo.setPay_app_id(order.optString("pay_app_id"));
                        weiXinPayInfo.setTotal_amount(order.optString("total_amount"));
                        weiXinPayInfo.setMethod("mobileapi.pay.weixinpay");
                        weiXinPayInfo.setToken(Run.TOKEN);
                        weiXinPayInfo.setUrl(Run.API_URL);
                        weChatPayHandle.callWXPay(weiXinPayInfo);
                        return;
                    }
                }
            } catch (Exception e) {
            }
        }

        @Override
        public JsonRequestBean task_request() {
            showLoadingDialog();
            return bean;
        }

    }

    private JsonRequestBean buildCreateOrderRequestBean(JSONObject payInfo) {
        try {
            double input = Double.parseDouble(etInput.getText().toString().trim());
//            if (input <= 0) {
//                Run.alert(mActivity, "输入金额必须大于0");
//                return null ;
//            }
            JSONObject payment = new JSONObject();
            payment.put("pay_app_id", payInfo.optString("app_id"));
            payment.put("app_pay_type", payInfo.optString("app_pay_type"));
            payment.put("payment_name", payInfo.optString("app_display_name"));
            JsonRequestBean bean = new JsonRequestBean("mobileapi.paycenter.dopayment")
                    .addParams("pay_object", "recharge")
                    .addParams("payment_pay_app_id", payInfo.optString("app_id"))
                    .addParams("payment_cur_money", String.valueOf(input));
            AgentApplication.getApp(mActivity).payMoney = String.valueOf(input);
            return bean;
        } catch (Exception e) {
            return null;
        }
    }

    private class GetChargeTerms implements JsonTaskHandler {

        @Override
        public void task_response(String json_str) {
            hideLoadingDialog_mt();
            try {
                all = new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity, all)) {
                    JSONArray child = all.optJSONArray("data");
                    LayoutInflater inf = mActivity.getLayoutInflater();
                    if (child != null && child.length() > 0) {
                        updatePayView(child);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {

            }
        }

        @Override
        public JsonRequestBean task_request() {
            showCancelableLoadingDialog();
            JsonRequestBean req = new JsonRequestBean(
                    "mobileapi.order.select_payment");
            req.addParams("platform", "wap");
            return req;
        }
    }

    private View.OnClickListener mPayListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getTag() != null) {
                JSONObject data = (JSONObject) v.getTag();
                final ViewGroup items = ((ViewGroup) mContainer.findViewById(R.id.fragment_charge_methods_container));

                // 选中当前付款方式
                payInfo = data;
                Log.i("obj===", all.toString());
                final JSONArray mArray = all.optJSONArray("data");
                for (int i = 0, c = items.getChildCount(); i < c; i++) {
                    CheckBox mCheckBox = (CheckBox) items.getChildAt(i).findViewById(R.id.cb_account_choose_alipay);
                    mCheckBox.setChecked(false);
                    final int j = i;
                    final RelativeLayout rl = (RelativeLayout) (items.getChildAt(i).findViewById(R.id.view_charge_item_wechat));
                    if (mActivity != null && isAdded()) {
                        rl.setBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.bg_enter_view));
                    }
                    mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            if (isChecked) {
                                Log.i("j===", j + "");
                                obj = mArray.optJSONObject(j);
                                Log.i("obj", obj.toString());
//                                    String pay_id=obj.optString("app_id");
//                                    Log.i("pay_id",pay_id);
                                if (mActivity != null && isAdded()) {
                                    rl.setBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.bg_enter_view_press));

                                }
                            } else {
                                if (mActivity != null && isAdded())
                                    rl.setBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.bg_enter_view));
                            }
                        }
                    });

                }
                ((CheckBox) v.findViewById(R.id.cb_account_choose_alipay)).setChecked(true);
            }
        }
    };

    private class CheckPayTask implements JsonTaskHandler {
        private JsonRequestBean bean;

        public CheckPayTask(JsonRequestBean bean) {
            this.bean = bean;
        }

        @Override
        public JsonRequestBean task_request() {
            showCancelableLoadingDialog();
            return bean;
        }

        @Override
        public void task_response(String json_str) {
            hideLoadingDialog_mt();
            mPaymentStatus = false;
            if (null != json_str){
                Log.d("test", "检查订单状态或余额支付" + json_str);
                try {
                    JSONObject all = new JSONObject(json_str);
                    JSONObject data = all.optJSONObject("data");

                    if (data.optString("status").equals("1")) {
                        mPaymentStatus = true;
                        Run.alert(getActivity(), "支付成功");
                    } else {
                        Run.alert(getActivity(), "支付失败");
                    }

                } catch (Exception e) {
                }
            }
            resetPaymentStatusView();
        }
    }


    /**
     * html充值
     */
//        private class ChargeTask implements JsonTaskHandler {
//
//            @Override
//            public void task_response(String json_str) {
//                hideLoadingDialog_mt();
//                try {
//                    JSONObject all = new JSONObject(json_str);
//                    if (!Run.checkRequestJson(mActivity, all)) {
//                        Run.startThirdPartyPayment(mActivity, all);
//                    } else {
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public JsonRequestBean task_request() {
//                showCancelableLoadingDialog();
//                JsonRequestBean req = new JsonRequestBean("mobileapi.paycenter.dopayment");
//                req.addParams("pay_object", "recharge");
//                req.addParams("payment_pay_app_id", mPayId);
//                req.addParams("payment_cur_money", mEditText.getText().toString());
//                return req;
//            }
//
//        }
//
    @Override
    public void onResume() {
        super.onResume();

        boolean pay = Run.loadOptionBoolean(mActivity, "WXPayResult", false);
        if (pay) {
            Run.savePrefs(mActivity, "WXPayResult", false);
            if (Run.loadOptionBoolean(mActivity, "PayResult", false)) {
                startActivity(AgentActivity.intentForFragment(mActivity, AgentActivity.FRAGMENT_ACCOUNT_ORDERS)
                        .putExtra(Run.EXTRA_VALUE, R.id.account_orders_shipping));
                getActivity().finish();
                mPaymentStatus = true;
            } else {
                // startActivity(AgentActivity.intentForFragment(mActivity,
                // AgentActivity.FRAGMENT_ACCOUNT_ORDERS).putExtra(
                // Run.EXTRA_VALUE, R.id.account_orders_paying));
                mPaymentStatus = false;
            }
            resetPaymentStatusView();
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        Util.savePrefs(mActivity, "isChecked", 0);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mPaymentStatus) {
//            Intent intent = new Intent(getActivity(), AgentActivity.class);
//            intent.putExtra(AgentActivity.EXTRA_FRAGMENT, AgentActivity.FRAGMENT_CAHARGE_METHODS);
//            intent.putExtra(DoActivity.EXTRA_SHOW_BACK, true);
            Intent data = new Intent();
            mActivity.setResult(Activity.RESULT_OK, data);
//            Toast.makeText(mActivity,"传出的值是"+Activity.RESULT_OK,Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onDestroyView() {

        super.onDestroyView();
    }

    // 付款失败，统一处理
    private void resetPaymentStatusView() {
        mChargeLinearLayout.setVisibility(View.GONE);
        findViewById(R.id.confirm_order_paystate).setVisibility(View.VISIBLE);
        if (!mPaymentStatus) {
//            ((Button) findViewById(R.id.confirm_order_pay_state_ok)).setText(R.string.confirm_order_goto_order_detail);
            ((TextView) findViewById(R.id.confirm_order_pay_state_text)).setText(R.string.confirm_order_pay_failed);
//            ((ImageView) findViewById(R.id.confirm_order_pay_state_icon)).setImageResource(R.drawable.pay_failed_face);
        } else {
            if (Run.isOfflinePayType(payInfo))
                ((TextView) findViewById(R.id.confirm_order_pay_state_text))
                        .setText(R.string.confirm_order_pay_offline);
        }
    }

}
